// app/db/base/baseEntity.js
const Database = require('better-sqlite3');
const fileHandle = require('@utils/fileHandle');
const logger = require('@utils/logger');
const QueryBuilder = require('@db/base/queryBuilder');
const colors = require('colors')

// 通用状态常量池
const ENTITY_STATUS = {
    DELETE_STATUS: {
        ACTIVE: 1,      // 活跃状态
        DELETED: 2  // 软删除状态
    },
};

class BaseEntity {

    // 状态常量挂载到类上（方便继承）
    static STATUS = ENTITY_STATUS;

    constructor(tableName) {
        this.db = new Database(fileHandle.getDBPath());
        this.tableName = tableName;
        this.softDeleteField = 'is_deleted'; // 可配置软删字段

        // 共享的PRAGMA设置（只需设置一次）
        this.db.pragma('journal_mode = WAL');
        this.db.pragma('synchronous = NORMAL');
        this.db.pragma('cache_size = -64000');
        this.db.pragma('temp_store = MEMORY');
        this.db.pragma('mmap_size = 268435456');
    }

    // 新增查询入口
    query() {
        // 直接传递当前实例（this）作为 model 参数，chain 默认为空数组
        // console.log(`is_deleted:[ ${this.softDeleteField} ]::[ ${this.constructor.STATUS.ACTIVE}]`.bgYellow);

        return new QueryBuilder(this, []); // 默认过滤软删
    }

    // 快捷方法
    findById(id) {
        return this.query().where('id', '$eq', id).first();
    }

    // 事务支持
    transaction(callback) {
        return this.db.transaction(callback);
    }

    // 其他通用方法（insert/getById/update等可根据需要添加）
    close() {
        this.db.close();
    }
}

module.exports = BaseEntity;